package com.ztjava.payali.controller;

import java.util.HashMap;
import java.util.Map;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.ztjava.core.Constant;
import com.ztjava.core.Jsub;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.member.FrontClient;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.core.utiliy.RequestUtil;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.pay.model.PayOrder;
import com.ztjava.pay.service.PayService;
import com.ztjava.pay.validator.PayValidator;

@ControllerClass(path="/pay/ali",client=FrontClient.class)
@UserController(portal=Constant.P_MEMBER)
public class PayaliFrontController extends BaseController{

	private static String gateway = "https://openapi.alipay.com/gateway.do";
	private static AlipayClient alipayClient = null;
	private static PayService payService = Duang.duang(PayService.class);

	private static final String PAY_ALI_PC_APP_ID = "PAY_ALI_PC_APP_ID";
	private static final String PAY_ALI_PC_APP_PRIVATE_KEY = "PAY_ALI_PC_APP_PRIVATE_KEY";
	private static final String PAY_ALI_PC_ALIPAY_PUBLIC_KEY = "PAY_ALI_PC_ALIPAY_PUBLIC_KEY";
	
	@Before(PayValidator.class)
	public void doPay(){
		PayOrder payOrder = getAttr("payOrder");
		if(alipayClient==null){
			alipayClient = new DefaultAlipayClient(gateway
					, ViewTool.param(PAY_ALI_PC_APP_ID)
					, ViewTool.param(PAY_ALI_PC_APP_PRIVATE_KEY), "json", "UTF-8"
					, ViewTool.param(PAY_ALI_PC_ALIPAY_PUBLIC_KEY), "RSA2"); //获得初始化的AlipayClient
		}
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(payOrder.getStr("redirect_url"));
		alipayRequest.setNotifyUrl(RequestUtil.getDomain(getRequest())+Jsub.path+getAttrForStr(Constant.PRE_PATH)+"/pay/ali/notifyResult");
		alipayRequest.setBizContent("{" +
		        "    \"out_trade_no\":\""+payOrder.getStr("num")+"\"," +
		        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
		        "    \"total_amount\":"+payOrder.getBigDecimal("money").doubleValue()+"," +
		        "    \"subject\":\""+payOrder.getStr("title")+"\"" +
		        "  }");
		 String form="";
		 try {
			 form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
		 } catch (AlipayApiException e) {
		     e.printStackTrace();
		 }
		 payService.payChoose(payOrder, "ALIPAY_PC");
		 renderHtml(form);
	}
	//支付成功通知
	public void notifyResult(){
        try {
			if(!AlipaySignature.rsaCheckV1(getParamsMap(getRequest().getParameterMap()),
					ViewTool.param(PAY_ALI_PC_ALIPAY_PUBLIC_KEY), "UTF-8", "RSA2")){
				return;
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			renderNull();
		}
		PayOrder payOrder = payService.getOrderByNum(getPara("out_trade_no",""));
		if(payOrder==null||!payOrder.getStr("status").equals("READY")){
			renderNull();
			return;
		}
		String trade_status = getPara("trade_status","");
		if(trade_status.equals("TRADE_SUCCESS")||trade_status.equals("TRADE_FINISHED")){
			payService.paySuccess(payOrder,getPara("trade_no"));
		}
		renderText("success");
	}
	
	private Map<String,String> getParamsMap(Map<String,String[]> requestMap){
		Map<String,String> params = new HashMap<String,String>();
        for (String key:requestMap.keySet()) {
            String[] values = (String[]) requestMap.get(key);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]: valueStr + values[i] + ",";
            }
            params.put(key, valueStr);
        }
        return params;
	}
}
